package com.cmsz.collection.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author panyaoan
 * @date 2019/12/13
 * @description ElasticsearchClientConfig
 */
@Configuration
public class ElasticsearchClientConfig {

    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchClientConfig.class);

    /**
     * elk集群地址
     */
    @Value("${elasticsearch.host}")
    private String hostName;
    /**
     * 端口
     */
    @Value("${elasticsearch.port}")
    private String port;
    /**
     * 集群名称
     */
    @Value("${elasticsearch.cluster.name}")
    private String clusterName;

    public TransportClient transPort = null;

    @Bean
    public TransportClient client() throws UnknownHostException {
        try {
            // 配置信息
            Settings esSetting = Settings.builder()
                    .put("cluster.name", clusterName)
                    .put("client.transport.sniff", true)
                    .build();

            transPort = new PreBuiltTransportClient(esSetting);
            String[] esIps = hostName.split(",");
            for (String esIp : esIps) {
                transPort.addTransportAddress(new TransportAddress(InetAddress.getByName(esIp),9300));
            }
            return transPort;
        } catch (Exception e) {
            logger.error("elasticsearch TransportClient create error!!!", e);
            e.printStackTrace();
            if (transPort != null){
                transPort.close();
            }
        }
        return transPort;
    }

}
